/** 通过审批 */
const db = require('db');
const superagent = require('superagent');
const moment = require('moment');
const getAccessToken = require('tools/dd/getAccessToken');
const { toUpdate } = require('tools/sqlString');
const log = require('tools/log');
const { sendMail } = require('nmailer');

module.exports = async ctx => {
    const { connection, run } = db.init();
    try {
        const id = ctx.params.id;
        const company = ctx.headers["company-id"];
        const access_token = await getAccessToken(company);
        const order = await queryOrder(id, run);
        const userInfo = await getUserInfo(access_token, order.commercialSpecialistId);
        await update(id, { orderStatus: '等待分发' }, run);
        await toMail(order, userInfo);
        await run('COMMIT');
        ctx.body = 'ok';
        ctx.status = 200;
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = error.status;
        ctx.body = error.err;
    }
    connection.end();
}

/** 查询订单数据 */
async function queryOrder(id, run) {
    const sql = `SELECT * FROM orders WHERE id=${id}`
    const result = await run(sql);
    if (result.err) {
        throw { err: result.err, status: 502 }
    }
    if (!result.rows[0]) {
        throw { err: '订单不存在', status: 503 };
    }
    return result.rows[0];
}

/** 发送邮件 */
async function toMail(order, userInfo) {
    if (!userInfo.email) {
        throw { status: 504, err: { sqlMessage: '邮件发送失败，请联系管理员设置企业邮箱' } }
    }

    await sendMail({
        to: getTo(order),
        cc: `${getCc(order)},${userInfo.name}<${userInfo.email}>`,
        subject: `【任务单】${order.orderNo}【${order.project}】${order.undertakingType}-${order.details}-${order.personDays}人天`,
        html: `
        <p>亲爱的${order.cooperationMode === '外包' ? '田总' : '张总'}：</p>
        <p>需求人天排期已通过，请安排制作，谢谢！</p>
        <h3>【任务单】${order.orderNo}【${order.project}】${order.undertakingType}-${order.details}-${order.personDays}人天</h3>
        <table border="1" cellspacing="0" cellpadding="5">
            <tr>
                <td style="width: 100px;">订单编号</td>
                <td>${order.orderNo}</td>
            </tr>
            <tr>
                <td>项目名称</td>
                <td>${order.project}</td>
            </tr>
            <tr>
                <td>承接类型</td>
                <td>${order.undertakingType}</td>
            </tr>
            <tr>
                <td>订单明细</td>
                <td>${order.details}</td>
            </tr>
            <tr>
                <td>人天总和</td>
                <td>${order.personDays}人天</td>
            </tr>
            <tr>
                <td>计划开始时间</td>
                <td>${moment(order.planStartTime).format('YYYY-MM-DD')}</td>
            </tr>
            <tr>
                <td>计划完成时间</td>
                <td>${moment(order.produceCompletionTime).format('YYYY-MM-DD')}</td>
            </tr>
        </table>
        `,
    })
}

function getTo(order) {
    if (order.cooperationMode === '外包') {
        return 'Yellen<yellen@firemonkeysoft.com>';
    } else {
        return '张晓东<zhangxiaodong@firemonkeysoft.com>';
    }
}

function getCc(order) {
    if (order.cooperationMode === '外包') {
        return '李川<lichuan@firemonkeysoft.com>,高娥<gaoe@firemonkeysoft.com>';
    } else {
        return '李川<lichuan@firemonkeysoft.com>,高娥<gaoe@firemonkeysoft.com>,Yellen<yellen@firemonkeysoft.com>';
    }
}

// =====================================================
async function update(id, body, run) {
    const sql = toSqlString(id, body);
    const result = await run(sql);
    if (result.err) {
        throw { err: result.err, status: 504 }
    }
}

function toSqlString(id, body) {
    const sql = `
        UPDATE orders SET ${toUpdate(body)}
        WHERE id = ${id}
    `;
    return sql;
}

/** 获取用户数据 */
function getUserInfo(access_token, userid) {
    return new Promise((resolve, reject) => {
        superagent.post('https://oapi.dingtalk.com/topapi/v2/user/get')
            .query({ access_token })
            .send({ userid })
            .end((error, res) => {
                try {
                    if (error) throw error;
                    if (res.body.errcode !== 0) throw res.body
                    resolve(res.body.result);
                } catch (error) {
                    reject({ status: 504, error, err: { sqlMessage: '没有找到员工数据' } })
                    // reject({ status: 504, err: error })
                }
            })
    })
}